﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Globalization;
using Wix.Aura.Common.CustomTypes;
using System.Xml.Serialization;

namespace Wix.Aura.Common {
	public static class XmlWriterExtensions {
		public static void WriteAttribute(this XmlWriter writer, string localName, string value) {
			if (!string.IsNullOrEmpty(value))
				writer.WriteAttributeString(localName, value);
		}

		public static void WriteAttribute(this XmlWriter writer, string localName, Guid value) {
			writer.WriteAttributeString(localName, value.ToString().ToUpper(CultureInfo.InvariantCulture));
		}

		public static void WriteAttribute(this XmlWriter writer, string localName, Guid? value) {
			if (value.HasValue)
				writer.WriteAttribute(localName, value.Value);
		}

		public static void WriteAttribute<T>(this XmlWriter writer, string localName, Nullable<T> value) where T : struct {
			if (value.HasValue)
				writer.WriteAttribute(localName, value.Value);
		}

		public static void WriteAttribute(this XmlWriter writer, string localName, int value) {
			writer.WriteAttributeString(localName, value.ToString(CultureInfo.InvariantCulture));
		}

		public static void WriteAttribute(this XmlWriter writer, string localName, int? value) {
			if (value.HasValue)
				writer.WriteAttribute(localName, value.Value);
		}

		public static void WriteElements<T>(this XmlWriter writer, IEnumerable<T> values) where T : IXmlSerializable {
			if (values != null)
				foreach (var value in values) {
					writer.WriteElement(value);
				}
		}

		public static void WriteElement<T>(this XmlWriter writer, T value) where T : IXmlSerializable {
			if (value != null)
				value.WriteXml(writer);
		}
	}
}
